/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;

/**
 *
 * @author avasquez
 */
public class ResultSetComboBoxModel extends AbstractListModel implements ComboBoxModel {

    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;
    private int numberOfRows;
    private String campoID;
    private String campoTexto;
    private boolean connectedToDatabase = false;
    String SQL = "";
    Object itemSeleccionado;

    public ResultSetComboBoxModel(Connection conn, String query, String campoID, String campoTexto) {
        try {
            // load database driver class
            // connect to database
            connection = conn;
            this.campoID=campoID;
            this.campoTexto=campoTexto;
            // create Statement to query database
            statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

            connectedToDatabase = true;
            // set query and execute it
            SQL = query;
            setQuery(SQL);
        } catch (SQLException ex) {
            Logger.getLogger(ResultSetComboBoxModel.class.getName()).log(Level.SEVERE, null, ex);
        }
    } // end constructor

    public void setSelectedItem(Object anItem) {
        if ((itemSeleccionado != null && !itemSeleccionado.equals( anItem )) || itemSeleccionado == null && anItem != null) {
	    itemSeleccionado = anItem;
	    fireContentsChanged(this, -1, -1);
        }
    }

    public Object getSelectedItem() {
        return itemSeleccionado;
    }

    public int getSize() {
        return numberOfRows;
    }

    public Object getElementAt(int index) {
        if (!connectedToDatabase) {
            throw new IllegalStateException("Not Connected to Database");
        }
        // obtain a value at specified ResultSet row and column
        try {
            resultSet.absolute(index + 1);
            return resultSet.getString(campoTexto);
        } // end try
        catch (SQLException sqlException) {
            sqlException.printStackTrace();
        } // end catch

        return "";
    }

    public String getCampoIdAt(int index){
        return getElementAt(index, campoID).toString();
    }

    public String getCampoTextoAt(int index){
        return getElementAt(index, campoTexto).toString();
    }

    public Object getElementAt(int index,String campo) {
        if (!connectedToDatabase) {
            throw new IllegalStateException("Not Connected to Database");
        }
        // obtain a value at specified ResultSet row and column
        try {
            resultSet.absolute(index + 1);
            return resultSet.getString(campo);
        } // end try
        catch (SQLException sqlException) {
            sqlException.printStackTrace();
        } // end catch

        return "";
    }

    public void setQuery(String query)
            throws SQLException, IllegalStateException {
        // ensure database connection is available
        if (!connectedToDatabase) {
            throw new IllegalStateException("Not Connected to Database");
        }

        // specify query and execute it
        resultSet = statement.executeQuery(query);
        this.SQL = query;
        // determine number of rows in ResultSet
        resultSet.last();                   // move to last row
        numberOfRows = resultSet.getRow();  // get row number
        fireContentsChanged(this, 0, numberOfRows);
    } // end method setQuery

    public void actualizar(){
        try {
            setQuery(this.SQL);
        } catch (SQLException ex) {
            Logger.getLogger(ResultSetComboBoxModel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalStateException ex) {
            Logger.getLogger(ResultSetComboBoxModel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    // close Statement and Connection               
    public void disconnectFromDatabase() {
        if (!connectedToDatabase) {
            return;
        }

        // close Statement and Connection            
        try {
            statement.close();
        //connection.close();
        } // end try                                 
        catch (SQLException sqlException) {
            sqlException.printStackTrace();
        } // end catch                               
        finally // update database connection status
        {
            connectedToDatabase = false;
        } // end finally                             
    } // end method disconnectFromDatabase
}
